package com.jsgt.greekfire.ui.entrust.fragment

import android.text.TextUtils
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseFragment
import com.fhx.core.goToActivity
import com.fhx.core.utils.LogUtils
import com.google.gson.Gson
import com.google.protobuf.ByteString
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.EntrustBean
import com.jsgt.greekfire.common.util.XLinearLayoutManager
import com.jsgt.greekfire.dao.model.IdentityBean
import com.jsgt.greekfire.dao.model.IdentityWallet
import com.jsgt.greekfire.dao.viewmodel.WalletViewModel
import com.jsgt.greekfire.event.EntrustEvent
import com.jsgt.greekfire.ui.entrust.AddEntrustActivity
import com.jsgt.greekfire.ui.entrust.adapter.EntrustNodeAdapter
import com.jsgt.greekfire.viewmodel.EntrustViewModel
import com.jsgt.greekfire.viewmodel.UserViewModel
import com.scwang.smartrefresh.header.MaterialHeader
import kotlinx.android.synthetic.main.fragment_entrust_node.*
import org.altoro.common.crypto.Sha256Sm3Hash
import org.altoro.common.crypto.SignUtils
import org.bouncycastle.util.encoders.Hex
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigInteger

class EntrustNodeFragment : BaseFragment() {
    private var wallet: IdentityWallet? = null
    private val entrustViewModel: EntrustViewModel by lazy {
        ViewModelProvider(this).get(EntrustViewModel::class.java)
    }
    private val entrustNodeAdapter by lazy {
        EntrustNodeAdapter(requireContext(), R.layout.item_entrust_node_list)
    }
    private val walletViewModel: WalletViewModel by lazy {
        ViewModelProvider(this).get(WalletViewModel::class.java)
    }
    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(this).get(UserViewModel::class.java)
    }
    private var identityBean: IdentityBean? = null

    override fun getLayoutId(): Int = R.layout.fragment_entrust_node
    override fun main() {
        refreshEntrust.autoRefresh()
        refreshEntrust.setRefreshHeader(MaterialHeader(context));
        refreshEntrust.setOnRefreshListener {
            entrustViewModel.getDelegateList("true");
        }
        rvEntrust.layoutManager = XLinearLayoutManager(context)
        rvEntrust.adapter = entrustNodeAdapter
        entrustNodeAdapter.addChildClickViewIds(R.id.tvPutEntrust)
        entrustNodeAdapter.setOnItemChildClickListener { adapter, view, position ->
            var data = entrustNodeAdapter.getItem(position)
            if (view.id == R.id.tvPutEntrust) {
                if (wallet != null && data != null) {
                    goToActivity<AddEntrustActivity> {
                        this.putExtra("node", "Node" + (position + 1))
                        this.putExtra("account_address", data!!.address)
                        this.putExtra("entrust_address", wallet!!.address)
                    }
                }
            }
        }


        entrustViewModel.undelegateaccountListData.observe(this, Observer {
            if (it != null && !TextUtils.isEmpty(it.raw_data_hex)) {
                try {
                    val cryptoEngine = SignUtils.fromPrivate(
                        Hex.decode(
                            BigInteger(identityBean?.getPriKeyByAES()).toString(16)
                        ), true
                    )
                    val rawData = Sha256Sm3Hash.of(Hex.decode(it.raw_data_hex))
                    val sig =
                        ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine.signHash(rawData.bytes)))
                    val signature = Hex.toHexString(sig.toByteArray())
                    it.signature = signature
                    var data = Gson()
                    entrustViewModel.broadcasttransaction(data.toJson(it))
                    /*    var privateKey = YTWalletUtils.getPrivateKey(identityBean?.getMnemonicByAES())
                        val rawData = Sha256Sm3Hash.of(Hex.decode(it.raw_data_hex))
                        val sig = ByteString.copyFrom(privateKey.Base64toBytes(privateKey.signHash(rawData.bytes)))
                        val signature = Hex.toHexString(sig.toByteArray())
                        it.signature = signature
                        var data = Gson()
                        entrustViewModel.broadcasttransaction(data.toJson(it))*/
                } catch (e: Exception) {
                    LogUtils.error(e.message)
                    e.printStackTrace()
                }
            }

        })
        walletViewModel.getSelectWallet()?.observe(this, Observer {
            if (it != null && it.isNotEmpty()) {
                wallet = it[0]
                userViewModel.getAccount(wallet?.address!!, "true")
            }
        })
        entrustViewModel.delegateListData.observe(this, Observer {
            try {
                if (it != null && it.size > 0) {
                    entrustNodeAdapter.setNewData(it as MutableList<EntrustBean>?)
                } else {
                    entrustNodeAdapter.setEmptyView(R.layout.item_entrust_empty)
                }
                if (refreshEntrust != null) {
                    refreshEntrust.finishRefresh();
                    refreshEntrust.finishLoadMore();//不传时间则立即停止刷新    传入false表示加载失败
                    refreshEntrust.finishLoadMoreWithNoMoreData();//没有加载更多
                }
            } catch (e: Exception) {
                LogUtils.error(e.message)
                e.printStackTrace()
            }
        })
        entrustViewModel.errorLiveData.observe(this, Observer {
            if (refreshEntrust != null) {
                refreshEntrust.finishRefresh();
                refreshEntrust.finishLoadMore();//不传时间则立即停止刷新    传入false表示加载失败
                refreshEntrust.finishLoadMoreWithNoMoreData();//没有加载更多
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEntrustEvent(e: EntrustEvent) {
        entrustViewModel.getDelegateList("true");
    }

}